﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.Interfaces;

namespace Model
{
    public class ProjectRepository : IProjectRepository
    {
        public ProjectRepository(IUser user, IDatabaseFacade databaseFacade)
        {
            _user = user;
            _databaseFacade = databaseFacade;
            GetActiveProjects();
        }

        private void GetActiveProjects()
        {
            _ActiveProjects = _databaseFacade.GetUserProjects(_user);
        }


        private IEnumerable<IProject> _ActiveProjects;
        private IUser _user;
        private IDatabaseFacade _databaseFacade;

        public event EventHandler RepositoryChanged;

        public void CreateProject(string projectName, string projectDescription = null)
        {
            if (_databaseFacade.AddProject(projectName, projectDescription))
                RepositoryChanged(this, null);
        }

        public void RemoveProject(IProject project)
        {
            if (_databaseFacade.DeleteProject(project))
                RepositoryChanged(this, null);
        }

        public IEnumerable<IProject> ActiveProjects
        {
            get
            {
                return _ActiveProjects;
            }
        }

        public void ModifyProject(IProject project)
        {
            if (_databaseFacade.EditProject(project))
            {
                var lastActiveProject = (from projects in _ActiveProjects
                                    where projects.Status == ProjectStatus.Active && projects != project
                                    select projects).ToList<IProject>();

               lastActiveProject[0].Status = ProjectStatus.NotActive;

                if (!_databaseFacade.EditProject(lastActiveProject[0]))
                    throw new ApplicationException("You screw it with DB and active projects!");

                GetActiveProjects();

                RepositoryChanged(this, null);
            }
           
        }
    }
}
